package com.baozun.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.StringUtils;

/**
 * 
 * @Title:
 * @Company:宝尊电子商务有限公司
 * @Description:
 * @Author:xiaozhou.zhou
 * @Since:2014年12月26日
 * @Copyright:Copyright (c) 2014
 * @ModifyDate:
 * @Version:1.1.0
 */
public class DataEncapsulation {
    
    /**
     * 将客户端提交的数据封装到Bean中
     * 
     * @param args 貌似是可以使用BeanUtils.copyProperties(T t,HttpServletRequest request);
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws InvocationTargetException
     */
    public static <T> T request2Bean(HttpServletRequest request, Class<T> beanClass) throws IllegalAccessException, InvocationTargetException, InstantiationException {
        T bean = beanClass.newInstance();
        request2Bean(request, bean);
        return bean;
    }
    
    public static <T> T copy2Bean(Object obj, Class<T> beanClass) {
        // TODO Auto-generated method stub
        try {
            T bean = beanClass.newInstance();
            Field[] fields = obj.getClass().getFields();
            for (Field field : fields) {
                
                String name = field.getName();
                String type = field.getType().getName();
                if (Integer.class.getName().equals(type)) {
                    int value = field.getInt(obj);
                    BeanUtils.setProperty(bean, name, value);
                } else if (Double.class.getName().equals(type)) {
                    double value = field.getDouble(obj);
                    BeanUtils.setProperty(bean, name, value);
                } else if (String.class.getName().equals(type)) {
                    String value = (String) field.get(obj);
                    BeanUtils.setProperty(bean, name, value);
                } else if (Date.class.getName().equals(type)) {
                    Date value = (Date) field.get(obj);
                    BeanUtils.setProperty(bean, name, value);
                }
                
            }
            return bean;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    public static <T> T map2Bean(Map<String, String> paramMap, Class<T> beanClass) throws IllegalAccessException, InvocationTargetException, InstantiationException {
        T bean = beanClass.newInstance();
        Set<Entry<String, String>> set = paramMap.entrySet();
        Iterator<Entry<String, String>> ite = set.iterator();
        // 给converter注册时间转换器
        ConvertUtils.register(new DateConverter(), Date.class);
        while (ite.hasNext()) {
            Entry<String, String> entry = ite.next();
            String key = entry.getKey();
            String value = entry.getValue();
            if (StringUtils.isNotEmpty(value)) {
                // 不为空
                BeanUtils.setProperty(bean, key, value);
            }
        }
        return bean;
    }
    
    /**
     * 将数据拷贝到bean中
     * 
     * @param request
     * @param bean
     * @param clazz
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static Object request2Bean(HttpServletRequest request, Object bean) throws IllegalAccessException, InvocationTargetException {
        // TODO Auto-generated method stub
        Enumeration<String> e = request.getParameterNames();
        // 给converter注册时间转换器
        ConvertUtils.register(new DateConverter(), Date.class);
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            String value = request.getParameter(name);
            // 这里无法处理时间参数
            BeanUtils.setProperty(bean, name, value);
        }
        return bean;
    }
}


class DateConverter implements Converter {
    
    @Override
    public Object convert(@SuppressWarnings("rawtypes") Class type, Object value) {
        if (value != null) {
            if (value instanceof String) {
                String str = (String) value;
                Date date = null;
                try {
                    if (str.length() == 10) {
                        // yyyy-MM-dd
                        date = new SimpleDateFormat("yyyy-MM-dd").parse(str);
                    } else if (str.length() == 19) {
                        // yyyy-MM-dd HH:mm:ss
                        date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str);
                    } else if (str.length() == 16) {
                        // yyyy-MM-dd HH:mm
                        date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(str);
                    } else if (str.length() == 7) {
                        date = new SimpleDateFormat("yyyy-MM").parse(str);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return date;
            } else if (value instanceof Date) {
                // 如果是时间类型直接返回
                return (Date) value;
            } else if (value instanceof Calendar) {
                return ((Calendar) value).getTime();
            } else {
                return null;
            }
        } else {
            return null;
        }
    }
    
}
